package com.seaboxdata.interfaceJob;

import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;
import com.robin.core.base.util.StringUtils;
import com.seaboxdata.entity.EmergencyResource;
import com.seaboxdata.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
@Slf4j
@Configuration
public class EmergencyResourceSynchronizer {
    private static final String utcPattern = "yyyy-MM-dd'T'HH:mm:ss.SSS";
    private static Gson gson = new Gson();
    @Value("${connector.daxin.vehicle.hazard.loginUrl}")
    private String loginUrl;
    @Value("${connector.daxin.vehicle.hazard.username}")
    private String username;
    @Value("${connector.daxin.vehicle.hazard.password}")
    private String password;
    @Value("${connector.daxin.vehicle.hazard.type}")
    private String type;
    @Value("${connector.daxin.vehicle.emergencyResource.emergencyResourceUrl}")
    private String emergencyResourceUrl;
    private String accessToken;

    public String doLoginRetToken() {
        try {
            String passwordInput = StringUtils.getMd5Encry(password);
            String accessToken = null;
            Map<String, String> contentMap = new HashMap<>();
            contentMap.put("username", username);
            contentMap.put("password", passwordInput.toLowerCase());
            contentMap.put("type", type);
            Map<String, String> headerMap = new HashMap<>();
            headerMap.put("content-type", "application/json");
            HttpUtils.Response response = HttpUtils.doPost(loginUrl, gson.toJson(contentMap), "UTF-8", headerMap);
            if (response.getStatusCode() == 200) {
                Map<String, Object> map = gson.fromJson(response.getResponseData(), new TypeToken<Map<String, Object>>() {
                }.getType());
                if (map.containsKey("message")) {
                    accessToken = map.get("message").toString();
                }
            }
            return accessToken;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public List<EmergencyResource> queryEmergencyResource() {
        if (accessToken == null) {
            accessToken = doLoginRetToken();
        }
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("content-type", "application/json");
        headerMap.put("Authorization", accessToken);
        HttpUtils.Response response = HttpUtils.doPost(emergencyResourceUrl,"{}", "UTF-8", headerMap);
        if (null != response) {
            if (response.getStatusCode() == 401) {
                accessToken = doLoginRetToken();
                headerMap.put("Authorization", accessToken);
            }
            if (response.getStatusCode() == 200) {
                Map<String, Object> map = gson.fromJson(response.getResponseData(), Map.class);
                Object c = map.get("code");
                List<EmergencyResource> emergencyresources = null;
                if (c != null) {
                    double code = Double.parseDouble(c.toString());
                    if (code == 1.0) {
                        LinkedTreeMap data = (LinkedTreeMap) map.get("data");
                        Object rows = data.get("rows");
                        emergencyresources = new ArrayList<>();
                        if (null != data) {
                            List<Map<String, Object>> list = (List) rows;
                            for (Map<String, Object> m : list) {
                                if (MapUtils.isNotEmpty(m)) {
                                    EmergencyResource emergencyResource = getEmergencyResource(m);
                                    emergencyresources.add(emergencyResource);
                                }
                            }
                        }
                    } else if (code == 0) {

                    }
                }
                return emergencyresources;
            } else {
                log.error(emergencyResourceUrl + " 调用失败！");
                return null;
            }
        }
        return null;
    }

    /**
     * 将map转为实体
     */
    private EmergencyResource getEmergencyResource(Map<String, Object> m) {
        EmergencyResource emergencyResource = new EmergencyResource();
        SimpleDateFormat simpleDateFormat =
                new SimpleDateFormat(utcPattern);
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        emergencyResource.setId(m.get("id").toString());
        emergencyResource.setName((String) m.get("name"));
        emergencyResource.setNum((Double) m.get("num") == null ? 0.0 : (Double) m.get("num"));
        emergencyResource.setType((String)((LinkedTreeMap) m.get("tbDicItemType")).get("name"));
        emergencyResource.setSite((String) m.get("site"));
        emergencyResource.setDutyPeople((String) m.get("dutyPeople"));
        emergencyResource.setDutyPhone((String) m.get("dutyPhone"));
        String validityTimeStr = (String) m.get("validityTime");
        Date validityTimeDate = null;
        try {
            validityTimeDate = validityTimeStr == null ? null : simpleDateFormat.parse(validityTimeStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        emergencyResource.setValidityTime(validityTimeDate);
        emergencyResource.setPurpose((String) m.get("use"));
        emergencyResource.setLevels((String)((LinkedTreeMap) m.get("tbDicItemLevel")).get("name"));
        emergencyResource.setSource((String) (m.get("qyName")));
        emergencyResource.setLat((String) (m.get("lat")));
        emergencyResource.setLon((String) (m.get("lon")));
        emergencyResource.setQyId((String) m.get("qyId"));
        emergencyResource.setCreatePeople((String) m.get("createPeople"));
        emergencyResource.setCjsj(new Date());
        String createTimeStr = (String) m.get("createTime");
        Date createTimeDate = null;
        try {
            createTimeDate = createTimeStr == null ? null : simpleDateFormat.parse(createTimeStr);;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        emergencyResource.setCreateTime(createTimeDate);
        emergencyResource.setIscompany((String) (m.get("iscompany")));
        emergencyResource.setEmail((String) (m.get("email")));
        emergencyResource.setFaxnumber((String) m.get("faxNumber"));
        return emergencyResource;
    }
}
